import { _decorator, Component, Node, ProgressBar } from 'cc';
import { GameTimer } from './Global';
const { ccclass, property } = _decorator;

@ccclass('ProgressTimer')
export class ProgressTimer extends Component {
    @property({ type: Number })
    totalTime: number = 0;

    // 时间上的单位长度
    #unit: number = 0;
    #progressBar: ProgressBar | null = null;
    start() {
        this.restart();
    }

    update(deltaTime: number) {

        if (GameTimer.state != 'playing') return
        GameTimer.time -= deltaTime;
        if (GameTimer.time <= 0) {
            GameTimer.stop();
        }
        // 更新进度条
        this.#progressBar.progress = (this.totalTime - GameTimer.time) * this.#unit / this.#progressBar.totalLength;
    }

    restart() {
        this.#progressBar = this.node.getComponent(ProgressBar)
        const totalLenth = this.#progressBar.totalLength;
        this.#unit = totalLenth / this.totalTime;

        // 初始化进度条
        GameTimer.play(this.totalTime);

    }

}


